package com.school.sports.filter;

import com.school.sports.service.Impl.AuthServiceImpl;
import com.school.sports.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;


import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT认证过滤器
 */
@Slf4j
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    @Lazy
    private AuthServiceImpl authService;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {

        final String requestTokenHeader = request.getHeader("Authorization");

        String username = null;
        String jwtToken = null;

        // JWT Token 格式为 "Bearer token"
        if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
            jwtToken = requestTokenHeader.substring(7);
            try {
                username = jwtUtil.getUsernameFromToken(jwtToken);
            } catch (Exception e) {
                log.warn("无法获取JWT Token中的用户名：{}", e.getMessage());
            }
        } else {
            log.debug("JWT Token不存在或格式不正确");
        }

        // 验证token
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            try {
                // 检查token是否在黑名单中
                if (authService.isTokenBlacklisted(jwtToken)) {
                    log.warn("Token已在黑名单中：{}", jwtToken);
                    filterChain.doFilter(request, response);
                    return;
                }

                UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

                // 如果token有效，配置Spring Security手动设置认证
                if (jwtUtil.validateToken(jwtToken, userDetails.getUsername())) {
                    UsernamePasswordAuthenticationToken authToken =
                            new UsernamePasswordAuthenticationToken(
                                    userDetails, null, userDetails.getAuthorities());
                    authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                    // 设置认证信息到SecurityContext
                    SecurityContextHolder.getContext().setAuthentication(authToken);

                    log.debug("用户 {} 已认证", username);
                }
            } catch (Exception e) {
                log.error("用户认证失败：{}", e.getMessage());
            }
        }

        filterChain.doFilter(request, response);
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        String path = request.getRequestURI();
        log.debug("当前请求路径：{}", path); // 新增日志，打印请求路径

        // 跳过认证的路径 - 由于设置了context-path，路径不需要加/api前缀
        return path.equals("/api/login") ||  // 新增这一行
                path.equals("/api/auth/login") ||
               path.equals("/api/auth/validate") ||
               path.startsWith("/api/public/") ||
               path.startsWith("/static/") ||
               path.startsWith("/css/") ||
               path.startsWith("/js/") ||
               path.startsWith("/images/") ||
               path.equals("/favicon.ico") ||
               path.equals("/error") ||
               // 额外处理OPTIONS请求（CORS预检请求）
               request.getMethod().equals("OPTIONS");
    }
}